package com.chinapost.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinapost.dao.BaseDaoI;
import com.chinapost.po.Tyglb;
import com.chinapost.service.YglbServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Yglb;

@Service("yglbService")
public class YglbServiceImpl implements YglbServiceI {
	
	private BaseDaoI<Tyglb> yglbDao;

	public BaseDaoI<Tyglb> getYglbDao() {
		return yglbDao;
	}

	@Autowired
	public void setYglbDao(BaseDaoI<Tyglb> yglbDao) {
		this.yglbDao = yglbDao;
	}

	@Override
	public void add(Yglb yglb) {
		Tyglb t = new Tyglb();
		BeanUtils.copyProperties(yglb, t);
		yglbDao.save(t);
	}

	@Override
	public void edit(Yglb yglb) {
		Tyglb t = yglbDao.get(Tyglb.class,yglb.getCid());
		t.setCname(yglb.getCname());
	}

	@Override
	public void delete(Yglb yglb) {
		String hql = "delete Tyglb t where t.cid =:id";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("id", yglb.getCid());
		yglbDao.executeHql(hql,params);
	}

	@Override
	public DataGrid datagrid(Yglb yglb) {
		DataGrid dg = new DataGrid();
		dg.setRows(listRows(find(yglb)));
		dg.setTotal(total());
		return dg;
	}

	private Long total() {
		String hql = "select count(*) from Tyglb t where 1=1";
		return yglbDao.count(hql);
	}

	private List<Tyglb> find(Yglb yglb) {
		String hql = "from Tyglb t where 1=1";
		if (yglb.getOrder() != null && yglb.getSort() != null) {
			hql += " order by " + yglb.getSort() + " " + yglb.getOrder();
		}
		return yglbDao.find(hql, yglb.getPage(), yglb.getRows());
	}

	private List<Yglb> listRows(List<Tyglb> lt) {
		List<Yglb> rows = new ArrayList<Yglb>();
		if (lt != null && lt.size() > 0) {
			for (Tyglb t : lt) {
				Yglb sub = new Yglb();
				BeanUtils.copyProperties(t, sub);
				rows.add(sub);
			}
		}
		return rows;
	}

	@Override
	public List<Yglb> combobox() {
		List<Yglb> rl = new ArrayList<Yglb>();
		List<Tyglb> l = yglbDao.find("from Tyglb");
		if (l != null && l.size() > 0) {
			for (Tyglb t : l) {
				Yglb r = new Yglb();
				r.setCid(t.getCid());
				r.setCname(t.getCname());
				rl.add(r);
			}
		}
		return rl;
	}

}

